#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class CowString{
    class CharProxy{
    public:
        CharProxy(CowString & self, size_t idx)
        : _self(self)   
        , _idx(idx)
        {}

        char & operator=(char ch);
        friend 
        ostream & operator<<(ostream & os, const CharProxy & rhs);
    private:
        CowString & _self;
        size_t _idx;
    };
public:
    CowString();
    ~CowString();
    CowString(const CowString & rhs);
    CowString(const char * pstr);
    CowString & operator=(const CowString & rhs);

    CharProxy operator[](size_t idx);

    const char * c_str() const{ return _pstr; }
    size_t size() const{ return strlen(_pstr); }
    int use_count() { return *(int*)(_pstr - kRefcountLength); }
    friend
        ostream & operator<<(ostream & os, const CowString & rhs);
    friend
        ostream & operator<<(ostream & os, const CharProxy & rhs);
private:
    char * malloc(const char * pstr = nullptr){
        if(pstr){
            return new char[strlen(pstr) + kRefcountLength + 1]()+ kRefcountLength;
        }else{
            return new char[1 + kRefcountLength]() + kRefcountLength;
        }
    }

    void release(){
        decreaseRefcount();
        if(use_count() == 0){
            delete [] (_pstr - kRefcountLength);
            _pstr = nullptr;
            cout << "delete heap" << endl;
        }
    }

    void initRefcount(){
        *(int*)(_pstr - kRefcountLength) = 1;
    }

    void increaseRefcount(){
        ++*(int*)(_pstr - kRefcountLength);
    }

    void decreaseRefcount(){
        --*(int*)(_pstr - kRefcountLength);
    }

    static const int kRefcountLength = 4;
    char * _pstr;
};

ostream & operator<<(ostream & os, const CowString & rhs){
    os << rhs._pstr ;
    return os;
}

CowString::CowString()
    : _pstr(malloc())
{
    cout << "CowString()" << endl; 
    initRefcount();
}

CowString::~CowString(){
    release();
}


CowString::CowString(const CowString & rhs)
    : _pstr(rhs._pstr)//浅拷贝
{
    increaseRefcount();
    cout << "CowString(const CowString&)" << endl;
}


CowString::CowString(const char * pstr)
    : _pstr(malloc(pstr))
{
    cout << "CowString(const char *)" << endl;
    strcpy(_pstr,pstr);
    initRefcount();
}

CowString & CowString::operator=(const CowString & rhs){
    if(this != &rhs){ //1.还需要考虑自复制
        cout << "CowString& operator=(const CowString&)" << endl;
        release(); //2.判断是否回收，原本空间的引用计数-1
        _pstr = rhs._pstr;  //3.浅拷贝
        increaseRefcount();
    }
    return *this;
}

CowString::CharProxy CowString::operator[](size_t idx){
    return CharProxy(*this,idx);
}


char & CowString::CharProxy::operator=(char ch){
    if(_idx < _self.size()){
        if(_self.use_count() > 1){
            //原本空间的引用计数-1
            _self.decreaseRefcount();
            //深拷贝
            char * ptemp = _self.malloc(_self._pstr);
            strcpy(ptemp,_self._pstr);
            //修改指向
            _self._pstr = ptemp;
            //初始化新空间的引用计数
            _self.initRefcount();
        }
        //执行写操作
        _self._pstr[_idx] = ch;
        return _self._pstr[_idx];
    }else{
        cout << "out of range" << endl;
        static char nullchar = '\0';
        return nullchar;
    }
}

ostream & operator<<(ostream & os, const CowString::CharProxy & rhs){
    if(rhs._idx < rhs._self.size()){
        os << rhs._self._pstr[rhs._idx];
    }else{
        os << "out of range";
    }
    return os;
}
#if 0
char & CowString::operator[](size_t idx){
    if(idx < size()){
        return _pstr[idx];
    }else{
        cout << "out of range" << endl;
        static char nullchar = '\0';
        return nullchar;
    }
}
#endif

void test0(){
    CowString str1("hello");
    CowString str2(str1);
    CowString str3(str1);
    


    //读操作不需要重新开辟空间
    cout << str1[0] << endl;
    /* operator<<(cout,str1.operator[](0)); */
    cout << str1.use_count() << endl;
    cout << str2.use_count() << endl;
    cout << str3.use_count() << endl;



    //如果有多个对象共享了空间
    //一个对象进行写操作应该重新开辟空间
    //也就是写时复制
    str1[0] = 'H';
    /* (str1.operator[](0)).operator=('H'); */

    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    cout << str1.use_count() << endl;
    cout << str2.use_count() << endl;
    cout << str3.use_count() << endl;

    str1[0] = 'X';
    cout << str1 << endl;



    //没有优化余地
    //不能共享空间
    //只有复制的时候，确定内容是相同的
    //才会共享空间
    /* CowString str5("hello"); */
    /* CowString str6("hello"); */


}

int main(void){
    test0();
    return 0;
}
